package com.bite.friend.service.user.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.bite.api.RemoteJudgeService;
import com.bite.api.domain.UserExeResult;
import com.bite.api.domain.dto.JudgeSubmitDTO;
import com.bite.common.core.constants.Constants;
import com.bite.common.core.domain.R;
import com.bite.common.core.enums.CodeType;
import com.bite.common.core.enums.QuestionResType;
import com.bite.common.core.enums.ResultCode;
import com.bite.common.core.utils.ThreadLocalUtil;
import com.bite.common.security.exception.ServiceException;
import com.bite.friend.domain.question.Question;
import com.bite.friend.domain.question.QuestionCase;
import com.bite.friend.domain.question.es.QuestionES;
import com.bite.friend.domain.user.UserSubmit;
import com.bite.friend.domain.user.dto.UserSubmitDTO;
import com.bite.api.domain.vo.UserQuestionResultVO;
import com.bite.friend.elasticsearch.QuestionRepository;
import com.bite.friend.manager.UserSubmitCacheManager;
import com.bite.friend.mapper.question.QuestionMapper;
import com.bite.friend.mapper.user.UserSubmitMapper;
import com.bite.friend.rabbit.JudgeProducer;
import com.bite.friend.service.user.IUserQuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;


@Service
public class UserQuestionServiceImpl implements IUserQuestionService {

    @Autowired
    private QuestionMapper questionMapper;

    @Autowired
    private UserSubmitMapper userSubmitMapper;

    @Autowired
    private QuestionRepository questionRepository;

    @Autowired
    private RemoteJudgeService remoteJudgeService;

    @Autowired
    private JudgeProducer judgeProducer;

    @Autowired
    private UserSubmitCacheManager userSubmitCacheManager;

    @Override
    public R<UserQuestionResultVO> submit(UserSubmitDTO userSubmitDTO) {
        CodeType type = CodeType.getInstance(userSubmitDTO.getProgramType());
        switch (Objects.requireNonNull(type)) {
            case JAVA:
                JudgeSubmitDTO judgeSubmitDTO = assembleJudgeSubmitDTO(userSubmitDTO);
                return remoteJudgeService.doJudgeJavaCode(judgeSubmitDTO);
            case CPP:
                break;
        }
        throw new ServiceException(ResultCode.JUDGE_NOT_SUPPORT);
    }

    @Override
    public boolean rabbitSubmit(UserSubmitDTO userSubmitDTO) {
        CodeType type = CodeType.getInstance(userSubmitDTO.getProgramType());
        switch (Objects.requireNonNull(type)) {
            case JAVA:
                JudgeSubmitDTO judgeSubmitDTO = assembleJudgeSubmitDTO(userSubmitDTO);
                judgeProducer.submit(judgeSubmitDTO);
                return true;
            case CPP:
                break;
        }
        throw new ServiceException(ResultCode.JUDGE_NOT_SUPPORT);
    }

    @Override
    public UserQuestionResultVO exeResult(Long examId, Long questionId, String currentTime) {
        Long userId = getUserId();
        UserSubmit userSubmit = userSubmitCacheManager.getUserSubmit(userId, questionId, examId, currentTime);

//        UserSubmit userSubmit = userSubmitMapper.getCurrentUserSubmit(userId, examId, questionId, currentTime);

        UserQuestionResultVO userQuestionResultVO = new UserQuestionResultVO();
        if (userSubmit == null) {
            userQuestionResultVO.setPass(QuestionResType.IN_JUDGE.getValue());
        } else {
            userQuestionResultVO.setErrMsg(userSubmit.getResult());
            userQuestionResultVO.setPass(userSubmit.getPass());
            if (StrUtil.isNotEmpty(userSubmit.getCaseJudgeRes())) {
                List<UserExeResult> list = JSONUtil.toList(userSubmit.getCaseJudgeRes(), UserExeResult.class);
                userQuestionResultVO.setExeResultList(list);
            }
        }

        return userQuestionResultVO;
    }


    // 组装传入参数
    private JudgeSubmitDTO assembleJudgeSubmitDTO(UserSubmitDTO userSubmitDTO) {
        JudgeSubmitDTO judgeSubmitDTO = new JudgeSubmitDTO();
        // 获取题目信息
        Long questionId = userSubmitDTO.getQuestionId();
        QuestionES questionES = questionRepository.findById(questionId).orElse(null);
        if (questionES == null) {
            Question question = questionMapper.selectById(questionId);
            if (question == null) {
                throw new ServiceException(ResultCode.QUESTION_NOT_EXIST);
            }
            questionES = new QuestionES();
            BeanUtil.copyProperties(question, questionES);
            questionRepository.save(questionES);
        }
        BeanUtil.copyProperties(questionES, judgeSubmitDTO);
        // 用户Id 竞赛Id 拼装完的代码 输入输出还没做
        judgeSubmitDTO.setUserId(getUserId());
        judgeSubmitDTO.setExamId(userSubmitDTO.getExamId());
        judgeSubmitDTO.setProgramType(userSubmitDTO.getProgramType());
        String assembleCode = assembleCode(userSubmitDTO.getSubmitCode(), questionES.getMainFunc());
        judgeSubmitDTO.setUserCode(assembleCode);
        // 组装输入输出
        List<QuestionCase> questionCaseList = JSONUtil.toList(questionES.getQuestionCase(), QuestionCase.class);
        List<String> inputList = questionCaseList.stream().map(QuestionCase::getInput).toList();
        judgeSubmitDTO.setInputList(inputList);
        List<String> outputList = questionCaseList.stream().map(QuestionCase::getOutput).toList();
        judgeSubmitDTO.setOutputList(outputList);
        return judgeSubmitDTO;
    }

    // 拼装Code
    private String assembleCode(String userCode, String mainFunc) {
        int lastIndex = userCode.lastIndexOf("}");
        if (lastIndex == -1) throw new ServiceException(ResultCode.QUESTION_MAIN_CODE_ERROR);
        String result = userCode.substring(0, lastIndex) + "\n" + mainFunc + "\n" + userCode.substring(lastIndex);
        return result;
    }

    private Long getUserId() {
        return ThreadLocalUtil.get(Constants.THREAD_LOCAL_USER_ID, Long.class);
    }
}
